import {Effect,Reducer,Subscription} from 'umi';
import {login,getUserInfo,getViewAuthority} from '@/services/user';
import {setCookie,getCookie} from '@/utils/cookie';
import {ImenuList} from '@/interface/user.d';
import menuList from '@/utils/menu';


//是否有用户信息
let  isUserInfo:boolean = false;

export interface UserModelState{
    isLogin:boolean,
    userInfo:{[propName:string]:any},
    userMenu:ImenuList[]
}

export interface UserModelType{
    namespace:'user',
    state:UserModelState,
    effects:{
        Login:Effect,
        eqit:Effect,
        getUserInfo:Effect,
        getViewAuthority:Effect
    },
    reducers:{
        save:Reducer<UserModelState>
    },
    subscriptions: { setup: Subscription };
}

const UserModel:UserModelType = {
    namespace:'user',
    state:{
        isLogin:false,
        userInfo:{},
        userMenu:[]
    },
    effects:{
        *Login({payload},{call,put}){
            //调登录接口  call 调接口  put  派发reducer
            let result = yield call(login,payload);
            if(result.code === 1){
                setCookie('token',result.token);
                //登录成功
                yield put({
                    type:'save',
                    payload:{isLogin:true}
                })
            }
        },
        *eqit({payload},{call,put}){

        },
        *getUserInfo({payload},{call,put}){
            // //获取个人信息
            let data = yield call(getUserInfo);
            if(data.code === 1){
                isUserInfo = true;
                yield put({
                    type:'save',
                    payload:{userInfo:data.data}
                })
                //获取的个人权限
                yield put({
                    type:'getViewAuthority',
                    payload:{user_id:data.data.user_id}
                })
            }
        },
        //在一个effect调用另一个effect,用put方法
        *getViewAuthority({payload},{call,put}){
            let result = yield call(getViewAuthority,payload.user_id);
            if(result.code === 1){
                //最终要渲染到左边的菜单数组
                let list:ImenuList[] = [];
                menuList.map(item => {
                    let children = item.children.filter(val => {
                        return result.data.findIndex((v:any) => val.meta.view_id === v.view_id) != -1
                    })
                    list.push({...item,children})
                })
                // list.filter(item =>item.children.length);
                yield put({
                    type:'save',
                    payload:{userMenu:list}
                })
            }
        }
    },
    reducers:{
        save(state, action) {
            return {
              ...state,
              ...action.payload,
            };
          }
    },
    subscriptions: {
        setup({ dispatch, history }) {
          return history.listen(({ pathname }) => {
                console.log(pathname);//addQuestion ===>  addUser
                //判断当前是否登录：1》 已经登录 进入到指定的界面  2》没有登录，去到登录
                let token = getCookie('token');
                if(token){
                    //已经登录  访问 /login ===》  /main
                    if(pathname === '/login'){
                        history.replace('/main');
                    }
                    //获取个人信息  如果已经有用户信息了,不再获取了
                    if(!isUserInfo){
                        dispatch({
                            type:'getUserInfo'
                        })
                    }
                }else{
                    //没有登录
                    if(pathname !== '/login'){
                        history.replace(`/login?redirect=${encodeURIComponent(pathname)}`)
                    }
                }

          });
        }
    }
}

export default UserModel